using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace 综合同步
{//网络包
    public enum DataType
    {
        NetConnected,
        NetClose,
        NetRecieve,
        LogInfo,
    }
    public enum ChannelType
    {
        ARC = 9001,
        TEMPERATURE,
        VIDEO,
        HANG,
        PRESS,
    }
    public enum PacketType
    {
        RUNNING,
        OpenDoor,
        CloseDoor,
        ShutDown,
        StationChange,
        TimeSync,
    }
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public class PACKAGE_INFO
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
        public char[] magic = "dinghantech\0".ToArray();        //包头标志
        public Int64 timestamp;                               //时间戳
        public uint packtype;                                 //包类型
        public uint datalen;                                  //数据长度
        public uint checkcode;                                //头校验
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] //1024*15
        public byte[] data = new byte[1];                     //数据，根据包类型解释

        public PACKAGE_INFO SetCheckCode()
        {
            checkcode = (uint)(magic.Sum(o=>o)+
                BitConverter.GetBytes(timestamp).
                Concat(BitConverter.GetBytes(packtype)).
                Concat(BitConverter.GetBytes(datalen)).Sum(o=>o));
            return this;
        }
        public byte[] FromPackage(byte[] pack_data)
        {
            datalen = (uint)pack_data.Length;
            timestamp = Convert.ToInt64((DateTime.Now - new DateTime(1970, 1, 1, 8, 0, 0, 0)).TotalSeconds);;
            SetCheckCode();
            byte[] data = new byte[Marshal.SizeOf(this)+pack_data.Length-1];
            ClassByteConvert.Class2CByte(this).CopyTo(data, 0);
            pack_data.CopyTo(data, Marshal.SizeOf(this) - 1);
            return data;
        }
        public static PACKAGE_INFO ToPackage(byte[] data)
        {
            PACKAGE_INFO info = ClassByteConvert.Byte2Class<PACKAGE_INFO>(data);
            info.data = new byte[info.datalen];
            data.CopyTo(info.data,Marshal.SizeOf(typeof(PACKAGE_INFO))-1);
            return info;
        }
    };
}